package com.ice.app.system.auth.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ice.app.system.auth.service.AuthService;
import com.ice.app.system.auth.vo.UiConfigVo;
import com.ice.app.system.entity.User;
import com.ice.app.system.mapper.MenuMapper;
import com.ice.app.system.utils.ConfigUtils;
import com.ice.app.system.utils.SysDateUtils;
import com.iceframework.core.base.BaseController;
import com.iceframework.core.entity.Result;

/**
 * 控制层： 权限校验
 * 
 * @author Palo
 *
 */
@RequestMapping("/jwt")
@RestController
public class AuthController extends BaseController {

	@Value("${web.jwt.token-header}")
	private String tokenHeader;

	@Autowired
	private AuthService authService;

	@Autowired
	private MenuMapper menuMapper;

	@PostMapping(value = "/token")
	public Result createAuthenticationToken(User user) throws Exception {
		logger.debug(user.getUsername() + " require logging...");
		final String token = authService.login(user);
		if (StringUtils.isNoneEmpty(token)) {
			// 获取资源
			List<String> resources = menuMapper.selectResourceByUserName(user.getUsername());
			// 获取系统配置
			UiConfigVo uiConfig = getUiConfig();
			return Result.newOne().setCode("200").add("token", token).add("resources", resources).add("uiConfig", uiConfig).add("accessTime", System.currentTimeMillis());
		} else {
			return Result.newOne().setCode("401").add("token", null);
		}
	}

	@GetMapping(value = "/refresh")
	public Result refreshAndGetAuthenticationToken(HttpServletRequest request) throws Exception {
		String token = request.getHeader(tokenHeader);
		String refreshedToken = authService.refresh(token);
		return Result.newOne().setCode("200").add("token", refreshedToken).add("accessTime", System.currentTimeMillis());
	}

	@GetMapping(value = "/verify")
	public boolean verify(@RequestParam("token") String token) throws Exception {
		return authService.validate(token);
	}

	@GetMapping(value = "/test")
	public boolean verify() throws Exception {
		System.err.println("测试");
		return true;
	}
	
	/**
	 * 获取前端配置
	 * @return
	 */
	private UiConfigVo getUiConfig() {
		UiConfigVo uiConfigVo = new UiConfigVo();
		String uiVersionCache = ConfigUtils.getCacheConfig("UI_Version");
		uiVersionCache = uiVersionCache == null ? String.valueOf(SysDateUtils.getSysDatetime().getTime()) : uiVersionCache;
		uiConfigVo.setUiVersion(uiVersionCache);
		return uiConfigVo;
	}
}